package com.example.wechat.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

import com.example.wechat.Moment;
import com.example.wechat.model.Friend;

public class WeChatDatabaseManager {
    private WeChatDatabaseHelper dbHelper;
    private SQLiteDatabase database;

    public WeChatDatabaseManager(Context context) {
        dbHelper = new WeChatDatabaseHelper(context);
    }

    public void open() {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    // 用户相关操作
    public long addUser(String username, String password, String nickname) {
        ContentValues values = new ContentValues();
        values.put(WeChatDatabaseHelper.COLUMN_USERNAME, username);
        values.put(WeChatDatabaseHelper.COLUMN_PASSWORD, password);
        values.put(WeChatDatabaseHelper.COLUMN_NICKNAME, nickname);
        return database.insert(WeChatDatabaseHelper.TABLE_USERS, null, values);
    }

    public boolean checkUser(String username, String password) {
        String[] columns = {WeChatDatabaseHelper.COLUMN_USER_ID};
        String selection = WeChatDatabaseHelper.COLUMN_USERNAME + " = ?";
        String[] selectionArgs = {username};
        
        Cursor cursor = database.query(WeChatDatabaseHelper.TABLE_USERS, columns, 
                selection, selectionArgs, null, null, null);
        
        boolean exists = cursor.moveToFirst();
        cursor.close();
        
        if (!exists) {
            return false;
        }
        
        // 检查密码
        selection = WeChatDatabaseHelper.COLUMN_USERNAME + " = ? AND " + 
                   WeChatDatabaseHelper.COLUMN_PASSWORD + " = ?";
        selectionArgs = new String[]{username, password};
        
        cursor = database.query(WeChatDatabaseHelper.TABLE_USERS, columns, 
                selection, selectionArgs, null, null, null);
        
        exists = cursor.getCount() > 0;
        cursor.close();
        return exists;
    }

    // 消息相关操作
    public long addMessage(int senderId, int receiverId, String content, int type) {
        ContentValues values = new ContentValues();
        values.put(WeChatDatabaseHelper.COLUMN_SENDER_ID, senderId);
        values.put(WeChatDatabaseHelper.COLUMN_RECEIVER_ID, receiverId);
        values.put(WeChatDatabaseHelper.COLUMN_MESSAGE_CONTENT, content);
        values.put(WeChatDatabaseHelper.COLUMN_TYPE, type);
        values.put(WeChatDatabaseHelper.COLUMN_TIMESTAMP, System.currentTimeMillis());
        return database.insert(WeChatDatabaseHelper.TABLE_MESSAGES, null, values);
    }

    public List<String> getMessages(int userId, int friendId) {
        List<String> messages = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        
        String query = "SELECT * FROM " + WeChatDatabaseHelper.TABLE_MESSAGES +
            " WHERE (" + WeChatDatabaseHelper.COLUMN_SENDER_ID + " = ? AND " + 
            WeChatDatabaseHelper.COLUMN_RECEIVER_ID + " = ?) OR (" + 
            WeChatDatabaseHelper.COLUMN_SENDER_ID + " = ? AND " + 
            WeChatDatabaseHelper.COLUMN_RECEIVER_ID + " = ?) " +
            "ORDER BY " + WeChatDatabaseHelper.COLUMN_TIMESTAMP + " ASC";
            
        Cursor cursor = db.rawQuery(query, new String[]{
            String.valueOf(userId), String.valueOf(friendId),
            String.valueOf(friendId), String.valueOf(userId)
        });
        
        if (cursor.moveToFirst()) {
            do {
                int senderId = cursor.getInt(cursor.getColumnIndex(WeChatDatabaseHelper.COLUMN_SENDER_ID));
                String content = cursor.getString(cursor.getColumnIndex(WeChatDatabaseHelper.COLUMN_MESSAGE_CONTENT));
                String senderName = senderId == userId ? "我" : "对方";
                messages.add(senderName + "：" + content);
            } while (cursor.moveToNext());
        }
        
        cursor.close();
        return messages;
    }

    // 好友相关操作
    public long addContact(int userId1, int userId2, String remark, String group) {
        ContentValues values = new ContentValues();
        values.put(WeChatDatabaseHelper.COLUMN_USER_ID_1, userId1);
        values.put(WeChatDatabaseHelper.COLUMN_USER_ID_2, userId2);
        values.put(WeChatDatabaseHelper.COLUMN_REMARK, remark);
        values.put(WeChatDatabaseHelper.COLUMN_GROUP, group);
        return database.insert(WeChatDatabaseHelper.TABLE_CONTACTS, null, values);
    }

    public List<String> getContacts(int userId) {
        List<String> contacts = new ArrayList<>();
        String[] columns = {WeChatDatabaseHelper.COLUMN_USER_ID_2, 
                          WeChatDatabaseHelper.COLUMN_REMARK};
        String selection = WeChatDatabaseHelper.COLUMN_USER_ID_1 + " = ?";
        String[] selectionArgs = {String.valueOf(userId)};
        
        Cursor cursor = database.query(WeChatDatabaseHelper.TABLE_CONTACTS, columns,
                selection, selectionArgs, null, null, null);
        
        while (cursor.moveToNext()) {
            int contactId = cursor.getInt(0);
            String remark = cursor.getString(1);
            contacts.add(remark != null ? remark : String.valueOf(contactId));
        }
        cursor.close();
        return contacts;
    }

    // 获取所有好友
    public List<Friend> getAllFriends() {
        List<Friend> friends = new ArrayList<>();
        String[] columns = {
            WeChatDatabaseHelper.COLUMN_USER_ID,
            WeChatDatabaseHelper.COLUMN_USERNAME,
            WeChatDatabaseHelper.COLUMN_NICKNAME,
            WeChatDatabaseHelper.COLUMN_AVATAR,
            WeChatDatabaseHelper.COLUMN_SIGNATURE
        };
        
        Cursor cursor = database.query(WeChatDatabaseHelper.TABLE_USERS, columns,
                null, null, null, null, null);
        
        while (cursor.moveToNext()) {
            Friend friend = new Friend();
            friend.setId(String.valueOf(cursor.getInt(0)));
            friend.setUsername(cursor.getString(1));
            friend.setNickname(cursor.getString(2));
            friend.setAvatar(cursor.getString(3));
            friend.setGroup("我的好友");
            friend.setRemark("");
            friend.setStatus("accepted");
            friends.add(friend);
        }
        cursor.close();
        return friends;
    }

    // 朋友圈相关操作
    public long addMoment(int publisherId, String content, String images) {
        ContentValues values = new ContentValues();
        values.put(WeChatDatabaseHelper.COLUMN_PUBLISHER_ID, publisherId);
        values.put(WeChatDatabaseHelper.COLUMN_MOMENT_CONTENT, content);
        values.put(WeChatDatabaseHelper.COLUMN_IMAGES, images);
        values.put(WeChatDatabaseHelper.COLUMN_PUBLISH_TIME, System.currentTimeMillis());
        return database.insert(WeChatDatabaseHelper.TABLE_MOMENTS, null, values);
    }

    public List<String> getMoments(int userId) {
        List<String> moments = new ArrayList<>();
        String[] columns = {WeChatDatabaseHelper.COLUMN_MOMENT_CONTENT, 
                          WeChatDatabaseHelper.COLUMN_IMAGES};
        String selection = WeChatDatabaseHelper.COLUMN_PUBLISHER_ID + " = ?";
        String[] selectionArgs = {String.valueOf(userId)};
        
        Cursor cursor = database.query(WeChatDatabaseHelper.TABLE_MOMENTS, columns,
                selection, selectionArgs, null, null, 
                WeChatDatabaseHelper.COLUMN_PUBLISH_TIME + " DESC");
        
        while (cursor.moveToNext()) {
            String content = cursor.getString(0);
            String images = cursor.getString(1);
            moments.add(content + (images != null ? " [图片]" : ""));
        }
        cursor.close();
        return moments;
    }

    public List<Moment> getAllMoments() {
        List<Moment> moments = new ArrayList<>();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(WeChatDatabaseHelper.TABLE_MOMENTS,
                null, null, null, null, null,
                WeChatDatabaseHelper.COLUMN_PUBLISH_TIME + " DESC");
        while (cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(WeChatDatabaseHelper.COLUMN_MOMENT_ID));
            int publisherId = cursor.getInt(cursor.getColumnIndex(WeChatDatabaseHelper.COLUMN_PUBLISHER_ID));
            String content = cursor.getString(cursor.getColumnIndex(WeChatDatabaseHelper.COLUMN_MOMENT_CONTENT));
            String imagePath = cursor.getString(cursor.getColumnIndex(WeChatDatabaseHelper.COLUMN_IMAGES));
            // 简单处理，点赞和评论数都为0
            moments.add(new Moment(id, publisherId, content, imagePath, 0, 0));
        }
        cursor.close();
        return moments;
    }
} 